package ftps

import (
	"fmt"

	"goftp.io/server/v2"
)

// FtpServer
type FtpServer struct {
	name   string
	port   int
	driver server.Driver
}

func NewFtpServer(name string, port int, driver server.Driver) *FtpServer {
	return &FtpServer{
		name:   name,
		port:   port,
		driver: driver,
	}
}

func (s *FtpServer) Serve(errCh chan error) {
	go s.serve(errCh)
}

func (s *FtpServer) serve(errCh chan error) {
	auth := &server.SimpleAuth{
		Name:     "admin",
		Password: "admin",
	}
	perm := server.NewSimplePerm("root", "root")

	opt := &server.Options{
		Name:   s.name,
		Port:   s.port,
		Driver: s.driver,
		Auth:   auth,
		Perm:   perm,
		Logger: &server.DiscardLogger{},
	}
	// serve ftp server
	ftpServer, err := server.NewServer(opt)
	if err != nil {
		errCh <- fmt.Errorf("new ftp falied, %s", err)
		return
	}
	err = ftpServer.ListenAndServe()
	if err != nil {
		errCh <- fmt.Errorf("listen ftp falied, %s", err)
		return
	}
}
